// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db=cloud.database()
const _=db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let openid = wxContext.OPENID;
  let action=event.action;

  //检查是不是新用户
  let proCount = await db.collection('userSign').where({
    openid: openid
  }).count();
  if (proCount.total != 1) {
    //如果是新用户初始化签到天数并加入数据库
    await db.collection('userSign').add({
      data: {
        openid: openid,
        totalDays:0,
        status:false,
        totalJf:0
      }
    });
  }

  //获取数据库的签到信息
  let proSign= await db.collection('userSign').where({
    openid:openid
  }).field({
    totalDays:true,
    status:true,
    totalJf:true
  }).get();

  let signData=proSign.data[0];
  switch(action){
    case 'get':
      return{
        signData
      }
    break;
    //点击签到，更新签到信息并获取
    case 'add':
    try{
      //获取数据库的签到信息
      let prosc = await db.collection('userSign').where({
        openid: openid,
        status: true,
      }).count();
      if(prosc.total==0){
        await db.collection('userSign').where({
          openid:openid
        }).update({
          data:{
            totalDays:_.inc(1),
            totalJf:_.inc(66),
            status:true
          }
        });


        return{
          code:0,
          signData:{
            totalDays:signData.totalDays+1,
            status:true,
            totalJf: signData.totalJf+66
          }
        }
      }

      else{
        return{
          code:1,
          errorMes:'今日已经签到'
        }
      }

    }catch(e){
      return {
        errorMes:'签到失败',
        code:1
      }
    }
    break;
  }
}